package com.hgyc.mom.generator.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.common.util.text.Convert;
import com.hgyc.mom.common.vo.Result;
import com.hgyc.mom.core.mybatis.QueryWrapperUtil;
import com.hgyc.mom.generator.entity.GenTable;
import com.hgyc.mom.generator.entity.GenTableColumn;
import com.hgyc.mom.generator.entity.GenTableInfoVO;
import com.hgyc.mom.generator.entity.GenTableParam;
import com.hgyc.mom.generator.service.GenTableColumnService;
import com.hgyc.mom.generator.service.GenTableService;
import freemarker.template.TemplateException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 * 
 * @author fwj
 */
@Slf4j
@RestController
@RequestMapping("/tool/gen")
@Tag(name = "代码生成接口", description = "代码生成接口")
public class GenController
{
    @Autowired
    private GenTableService genTableService;

    @Autowired
    private GenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
    @GetMapping("/list")
    public Result<IPage<GenTable>> genList(GenTableParam genTableParam) {
        Page<GenTable> page = new Page<>(genTableParam.getPage(), genTableParam.getPageSize());
        GenTable genTable = new GenTable();
        BeanUtils.copyProperties(genTableParam, genTable);
        QueryWrapper<GenTable> wrapper = QueryWrapperUtil.build(genTable);
        IPage<GenTable> list = genTableService.page(page, wrapper);
        return Result.success(list);
    }

    @GetMapping("/all")
    public Result<List<GenTable>> allGenTable() {
        List<GenTable> list = genTableService.list();
        return Result.success(list);
    }

    /**
     * 修改代码生成业务
     */
    @GetMapping(value = "/{tableId}")
    public Result<?> getInfo(@PathVariable Long tableId) {
        try {
            GenTable table = genTableService.selectGenTableById(tableId);
            List<GenTable> tables = genTableService.selectGenTableAll();
            List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
            Map<String, Object> map = new HashMap<>();
            map.put("info", table);
            map.put("rows", list);
            map.put("tables", tables);
            return Result.success(map);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
            throw new BizException("获取表信息失败！");
        }

    }

    /**
     * 查询数据库列表
     */
    @GetMapping("/db/list")
    @Operation(summary = "分页数据库表信息", description = "分页数据库表信息")
    public Result<IPage<GenTable>> dataList(GenTableParam genTableParam) {
        IPage<GenTable> list = genTableService.selectDbTableList(genTableParam);
        return Result.success(list);
    }

    /**
     * 查询数据表字段列表
     */
    @GetMapping(value = "/column/{tableId}")
    public Result<List<GenTableColumn>> columnList(@PathVariable("tableId") Long tableId) {
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        return Result.success(list);
    }

    /**
     * 获取子表信息
     * @return 子表
     */
    @GetMapping(value = "/children/{tableName}")
    public Result<List<GenTable>> getChildrenTable(@PathVariable("tableName") String tableName) {
        List<GenTable> childrenTables = genTableService.getChildrenTable(tableName);
        return Result.success(childrenTables);
    }

    /**·
     * 导入表结构（保存）
     */
    @PostMapping("/importTable")
    public Result importTableSave(@RequestParam("tables") String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return Result.success();
    }

    /**
     * 修改保存代码生成业务
     */
    @PutMapping
    public Result<?> editSave(@Validated @RequestBody GenTableInfoVO genTable) {
        try {
            genTableService.validateEdit(genTable);
            genTableService.updateGenTable(genTable);
        } catch (JsonProcessingException e) {
            log.error("保存失败", e);
            throw new BizException("保存失败！");
        }

        return Result.success();
    }

    /**
     * 删除代码生成
     */
    @DeleteMapping("/{tableIds}")
    public Result<?> remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return Result.success();
    }

    /**
     * 预览代码
     */
    @GetMapping("/preview/{tableName}")
    public Result<?> preview(@PathVariable("tableName") String tableName) throws IOException
    {
        Map<String, String> dataMap = genTableService.previewCode(tableName);
        return Result.success(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException, TemplateException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */
    @GetMapping("/genCode/{tableName}")
    public Result<?> genCode(@PathVariable("tableName") String tableName)
    {
        try {
            genTableService.generatorCode(tableName);
        } catch (JsonProcessingException e) {
            log.error("生产代码失败", e);
            throw new BizException(e.getMessage());
        }
        return Result.success();
    }

    /**
     * 同步数据库
     */
    @GetMapping("/synchDb/{tableName}")
    public Result<?> synchDb(@PathVariable("tableName") String tableName)
    {
        genTableService.synchDb(tableName);
        return Result.success();
    }

    /**
     * 批量生成代码
     */
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, @RequestParam("tables") String tables) throws IOException, TemplateException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"hgyc.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}